package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.Executors;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    /**
     * 查询列表
     * @param DTO
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO DTO) {
        //1.参数校验
        if (DTO==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.分页查询
        Page<ApUserRealname> page = new Page<>(DTO.getPage(), DTO.getSize());
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //3.判断状态
        if (DTO.getStatus()!=null){
            //执行查询
            queryWrapper.eq(ApUserRealname::getStatus,DTO.getStatus());
        }
        IPage<ApUserRealname> pageresult = this.page(page, queryWrapper);
        //4.返回封装的结果
        return new PageResponseResult(DTO.getSize(),DTO.getPage(),pageresult.getTotal(),pageresult.getRecords());
    }

    //依赖注入
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 根据状态来进行审核
     * @param dto
     * @param status
     * @return
     */
    //@Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000) //开启全局事务
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, short status) {
        //1.参数检验
        if (dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数为空");
        }
        //2.根据id查询用户信息
        ApUserRealname apuser = this.getById(dto.getId());
        //2.1如果id无对应信息，报出异常
        if (apuser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        }
        //2.2判断用户状态（1.未审核，2.审核失败 9.审核成功）
        if (!AdminConstants.WAIT_AUTH.equals(apuser.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不是未审核状态");
        }
        //2.3根据实名认证的userid，查询出用户信息
        ApUser user = apUserMapper.selectById(apuser.getId());
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未发现用户信息");
        }
        //2.4修改实名认证的状态
        apuser.setStatus(status);
        apuser.setReason(dto.getMsg());
        //更新用户状态
       this.updateById(apuser);
        //3.如果审核通过
        if (AdminConstants.PASS_AUTH.equals(status)){
            //3.1创建自媒体账号
         WmUser wmUser = createWmUser(user);
            //3.2创建app端用户账号信息
            createAuthor(wmUser,user);
        }
        //整个异常
        if (dto.getId().intValue()==5){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不能等于5");
        }
        //4.返回结果
        return ResponseResult.okResult();
    }

    //依赖注入
    @Autowired
    private WemediaFeign wemediaFeign;
    /**
     * 创建自媒体账户
     * @param user
     * @return
     */
    private WmUser createWmUser(ApUser user) {
        //1.根据用户名，远程查询自媒体账户信息
        ResponseResult<WmUser> name = wemediaFeign.findByName(user.getName());
        if (!name.checkCode()){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"数据异常");
        }
        //1.1获取到账户信息
        WmUser wmUser = name.getData();
        //2.如果用户存在，注册失败
       if (wmUser!=null){
           CustException.cust(AppHttpCodeEnum.DATA_EXIST,"该用户信息已经存在");
       }
        //3.如果不存在就创建自媒体账户
        wmUser = new WmUser();
        wmUser.setApUserId(user.getId());
        wmUser.setName(user.getName());
        wmUser.setPassword(user.getPassword());
        wmUser.setSalt(user.getSalt());
        wmUser.setImage(user.getImage());
        wmUser.setPhone(user.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        //4.远程保存到自媒体中
        ResponseResult<WmUser> result = wemediaFeign.save(wmUser);
        //判断远程调用是否出错
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //5.接收返回结果
        return result.getData();
    }

    //依赖注入
    @Autowired
    private ArticleFeign articleFeign;
    /**
     * 创建作者信息
     * @param wmUser
     * @param user
     */
    private void createAuthor(WmUser wmUser, ApUser user) {
        //1.根据ApUserId远程查询作者信息
        ResponseResult<ApAuthor> userId = articleFeign.findByUserId(user.getId());
        if (!userId.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //2.获取到作者信息
        ApAuthor author = userId.getData();
        //3.判断作者信息是否已经存在
        if (author!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在");
        }
        //4.如果不存在就创建作者信息
        author = new ApAuthor();
        author.setName(user.getName());
        author.setType(AdminConstants.AUTHOR_TYPE);
        author.setUserId(user.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());

        //5.保存结果
        ResponseResult result = articleFeign.save(author);
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }
}
